<template>
  <div>
    <fks-empty v-if="showErrorReq">{{ errorReqMsg }}</fks-empty>

    <div v-else>
      <!-- form项json解析成html -->
      <parser
        ref="parser"
        :key="key"
        :form-conf.sync="formConf"
        :flow-conf="isFakeCustom ? {} : formPermission"
        :detail-permission="detailPermission"
        @form-data="getFormData"
        @openAssociate="openAssociateDialog"
      />
      <!-- 审批人渲染 -->
      <custom-assignee
        ref="custom_assignee"
        v-if="!isFakeCustom"
        :validate.sync="customFlowConfig.validate"
        :assigneeList.sync="customFlowConfig.customAssigneeList"
        :customAssigneeGroup.sync="customFlowConfig.customAssigneeGroup"
        :modelKey="modelKey"
      ></custom-assignee>
      <!-- comment 意见输入 -->
      <div class="comments-wrapper">
        <fks-row
          :gutter="15"
          v-if="
            !isFakeCustom &&
            comments.length > 0 &&
            type == 'execute' &&
            taskKey !== 'fawkes_custom_flow_start'
          "
        >
          <fks-form ref="form" label-width="92px">
            <fks-col :span="24">
              <fks-form-item :label="LANG.ADVICE" prop="comment">
                <fks-input
                  type="textarea"
                  style="width: 101%"
                  :rows="2"
                  v-model="comment"
                  maxlength="100"
                  show-word-limit
                ></fks-input>
              </fks-form-item>
            </fks-col>
          </fks-form>
        </fks-row>
        <fks-skeleton
          style="width: 100%; margin-top: 16px"
          v-if="!isFakeCustom && type == 'execute' && comments.length == 0"
          animated
        >
          <template #template>
            <div style="height: 54px">
              <fks-skeleton-item variant="text" style="height: 100%" />
            </div>
          </template>
        </fks-skeleton>
      </div>
      <div class="flow-comments-wrapper">
        <!-- 流程comments -->
        <fks-flow-comments
          v-if="type !== 'add' && !isFakeCustom && comments.length > 0"
          class="no-flow-chart"
          :flowInfo="flowInfo"
          :data="comments"
          :dataSerise="commentSeries"
        ></fks-flow-comments>
        <fks-skeleton
          style="width: 100%; margin-top: 16px"
          v-if="type !== 'add' && !isFakeCustom && comments.length == 0"
          animated
        >
          <template #template>
            <div style="height: 142px; margin-top: 70px">
              <fks-skeleton-item variant="text" style="height: 100%" />
            </div>
            <div style="height: 142px; margin-top: 42px">
              <fks-skeleton-item variant="text" style="height: 100%" />
            </div>
          </template>
        </fks-skeleton>
      </div>
      <fks-dialog
        title="流程图"
        :visible.sync="flowCanvasVisible"
        :append-to-body="true"
        width="960px"
        top="8vh"
        height="800px"
        v-cloak
      >
        <customFlowCanvas
          v-if="modelKey"
          :taskId="taskId"
          :bizId="bizId"
          :modelKey="modelKey"
          :flowInfo="flowInfo"
        ></customFlowCanvas>
      </fks-dialog>
      <associateDataDialog
        :visible.sync="associateDataVisible"
        :fieldvModel="clickModel"
        @mapFormData="mapFormData"
      ></associateDataDialog>
    </div>
  </div>
</template>

<script>
import Mix from '@/mixins/module'
import emmiter from 'fawkes-lib/lib/mixins/emitter'
import FlowButton from '@/modules/FormCenter/componentsWp/FlowButton/flowButton'
import customAssignee from '@/modules/FormCenter/componentsWp/CustomAssignee/index.vue'
import Parser from '@/modules/FormCenter/componentsWp/parser/Parser.vue'
import {
  getProcessHistory,
  getUserTaskDetail,
  initialCustomForm,
  submitCustomForm,
  getCustomFormConfig,
  getHistoryCustomFormConfig,
  getNodePermission,
  getHistoryNodes,
  getAssociateData
} from '../../api'
import customFlowCanvas from '../customFlowDiagram'
import associateDataDialog from '../AssociateData/dialog.vue'
// import downloadPdf from '@/utils/htmlToPdf'
import { getCurrentUser, unique, transfer } from '../../common'
import { isJSON } from '@/utils/util'
import eventBus from '../FlowButton/eventBus'
import cloneDeep from 'lodash.clonedeep'
export default {
  //自由流程表单 组件
  name: 'FormCenter',
  componentName: 'FormCenter',
  mixins: [Mix, emmiter],
  provide() {
    return {
      parentComponent: this
    }
  },
  components: {
    Parser,
    FlowButton,
    customAssignee,
    customFlowCanvas,
    associateDataDialog
  },
  props: ['formDesign'],
  data() {
    return {
      //上传文件时不允许提交表单相关
      uploadingList: [],
      buttonLoading: false,

      loading: true,
      showErrorReq: false,
      errorReqMsg: '请求表单数据失败',
      isFakeCustom: false, // 是否是需要customForm组件解析的普通流程表单
      flowCanvasVisible: false,
      associateDataVisible: false,
      clickModel: '', // 点击的关联数据组件的__vModel__
      mapRules: [], // 关联数据组件的映射规则
      formConf: {},
      customFlowConfig: {
        customAssigneeGroup: {},
        customAssigneeList: [],
        validate: true,
        isCustom: false
      },
      modelKey: '', // 流程的modelKey
      comment: '', // 流程评论内容
      processInstanceId:
        this.$route.params.processInstanceId ||
        this.$route.query.processInstanceId ||
        '', // 流程实例ID
      type: this.$route.params.type || 'view', // 表单类型
      bizId: this.$route.params.bizId || '', // 表单实例ID
      comments: [], // 表单评论信息
      formKey: this.$route.params.formKey || '', // 表单键值
      taskKey: this.$route.params.taskKey || '', // 任务键值
      taskId: this.$route.params.taskId || '', // 任务ID
      printFlag: this.$route.query.printFlag,
      commentSeries: {
        taskName: 'taskName',
        userName: 'asignee',
        realName: 'asigneeName',
        solveType: 'approveStateName',
        approveDate: 'approveDate',
        createDate: 'createDate',
        flag: 'approveState',
        comment: 'comment',
        delegateList: 'delegateList'
      },
      flowInfo: {
        xml: ''
      },
      // 输入此表单数据表对应的实体对象名
      entityName: '',
      // 表单数据
      formData: {},
      taskNodeName: this.$route.query.taskName || '', // 当前任务节点名称
      formPermission: {}, // 当前任务节点 表单项权限
      detailPermission: {}, //明细表在当前任务节点的权限
      formName: '', //表单名称
      key: +new Date(),
      //打印
      linkageData: [], // 请求到的关联数据
      isPreview: this.$route.path.includes('templatePreview')
    }
  },
  computed: {
    uploadingListLength() {
      return this.uploadingList.length
    }
  },
  watch: {
    uploadingListLength(val) {
      if (val !== 0) {
        this.buttonLoading = true
      } else {
        this.buttonLoading = false
      }
    }
  },
  methods: {
    //表单弹窗 关闭
    close() {
      this.$router.replace(this.$route.fullPath.match(/(\S*)\/customForm/)[1])
    },
    // parse组件传来的数据
    getFormData(val) {
      this.formData = val
    },
    //表单暂存
    saveDraft() {
      this.submitForm('SAVEDRAFT')
    },
    //流程发起前的表单提交
    submit() {
      //提交表单前 先进行表单校验
      this.$refs.parser.$refs.fksForm.validate(async (valid) => {
        //校验不通过直接return并提示错误
        let checkDetailForm = await this.checkDetailForm()
        if (!valid || !checkDetailForm) {
          this.$message({
            type: 'error',
            message: '请完善表单项！',
            showClose: true
          })
          return
        }
        this.submitForm('SUBMIT')
      })
    },
    submitForm(type = 'SUBMIT') {
      //通过后执行后续逻辑
      this.broadcast('FormUpload', 'setG9s')
      let formData = cloneDeep(this.formData)
      //校验通过，则获取表单数据 进行提交
      for (const key in formData) {
        if (typeof formData[key] === 'object') {
          formData[key] = JSON.stringify(formData[key])
        }
      }
      // 增加选人选部门搜索字段，给填写信息组件直接赋值
      let userObj = {}
      this.formConf.fields.forEach((item) => {
        let { __config__ = {} } = item
        if (!__config__.tagAttribute) {
          return
        }
        if (__config__.tagAttribute === 'user-selector') {
          let key = item.__vModel__ + '_value'
          let value =
            __config__.defaultValue && __config__.defaultValue.userfullname
              ? __config__.defaultValue.userfullname
              : ''
          userObj[key] = value
        } else if (__config__.tagAttribute === 'org-selector') {
          let key = item.__vModel__ + '_value'
          let value =
            __config__.defaultValue && __config__.defaultValue.deptName
              ? __config__.defaultValue.deptName
              : ''
          userObj[key] = value
        } else if (__config__.tagAttribute === 'association-form') {
          if (__config__.required) {
            item.__config__.defaultValue.forEach((item) => {
              let obj = JSON.parse(JSON.stringify(item))
              this.$delete(obj, 'create_by_full_name')
              this.$delete(obj, 'create_date')
              this.$delete(obj, 'update_by_full_name')
              this.$delete(obj, 'id')
              formData = {
                ...formData,
                ...obj
              }
            })
          } else {
            item.__config__.defaultValue
              ? item.__config__.defaultValue.forEach((item) => {
                  let obj = JSON.parse(JSON.stringify(item))
                  this.$delete(obj, 'create_by_full_name')
                  this.$delete(obj, 'create_date')
                  this.$delete(obj, 'update_by_full_name')
                  this.$delete(obj, 'id')
                  formData = {
                    ...formData,
                    ...obj
                  }
                })
              : ''
          }
        }
        if (__config__.tagAttribute === 'information' && this.type == 'add') {
          // 填写信息组件在发起时赋值
          let val = {}
          val.userFullname = this.$store.state.user.userFullname || ''
          val.prjDepName = ''
          val.createDate = new Date()
          val.userTelephoneNum = this.$store.state.user.phone || ''
          let orgList = this.$store.state.user.orgList || []
          orgList.forEach((item) => {
            if (item.id == this.$store.state.portal.id) {
              val.prjDepName = item.name
            }
          })
          formData[item.__vModel__] = JSON.stringify(val)
        }
      })
      let result = {
        ...formData,
        ...userObj
      }
      const $currentUser = Object.assign({}, getCurrentUser()) // 获取当前登录人信息的方法（根据实际需要可以进行修改）
      let initiateInfo = {
        fawkes_custom_flow_start: $currentUser.userName,
        fawkes_custom_flow_start_fullName: $currentUser.userFullname
      }
      let data = {
        formCommitParam: {
          formData:
            this.type === 'add'
              ? result
              : Object.assign(result, { id: this.bizId }),
          formKey: this.formKey
        },
        formProcessParam: {
          bizId: this.type === 'add' ? '' : this.bizId,
          comment: this.comment,
          formKey: this.formKey,
          modelKey: !this.isFakeCustom
            ? this.modelKey
            : 'FAWKES_ORDINARY_FORM_PROCESS',
          processInstanceId: this.processInstanceId,
          stageFlag: type === 'SAVEDRAFT' ? 1 : 0,
          taskId: this.taskId,
          variable: !this.isFakeCustom
            ? Object.assign(this.customFlowConfig.customAssigneeGroup, formData)
            : Object.assign(initiateInfo, formData),
          sysBpmCustomNodeDetailList: this.customFlowConfig.customAssigneeList
        }
      }
      eventBus.$emit('setLoading', true)
      submitCustomForm(data)
        .then((res) => {
          eventBus.$emit('setLoading', true)
          if (res.status) {
            this.onSuccess(type)
          } else {
            this.onError()
          }
        })
        .catch((err) => {
          console.log(err)
          eventBus.$emit('setLoading', true)
        })
    },
    // 校验明细表
    checkDetailForm() {
      let tabelDetailRefs = Object.keys(this.$refs.parser.$refs).filter(
        (ref) => {
          return ref.includes('detailTable')
        }
      )
      let validateArr = []
      tabelDetailRefs.forEach((item, idnex) => {
        let ref = new Promise((resolve, reject) => {
          this.$refs.parser.$refs[item].$refs.detailTable[0].$refs[
            'detail-table'
          ].validate((valid) => {
            if (valid) {
              resolve(true)
            } else {
              reject(false)
            }
          })
        })
        validateArr.push(ref)
      })
      return Promise.all(validateArr)
        .then(() => {
          return true
        })
        .catch(() => {
          return false
        })
    },
    onSuccess(type) {
      this.$message({
        type: 'success',
        message: (this.LANG[type] || '') + this.LANG.SUCCESS,
        showClose: true
      })
      this.$emit('success')
    },
    onError() {
      eventBus.$emit('setLoading', false)
    },
    //根据当前taskId 查询当前节点表单字段权限信息
    getNodePermission() {
      return new Promise((resolve, reject) => {
        let taskKey = this.$route.params.taskKey
          ? this.$route.params.taskKey
          : 'fawkes_custom_flow_start'
        getNodePermission({ modelKey: this.modelKey, taskKey: taskKey }).then(
          (res) => {
            if (res.status) {
              resolve(res.data)
            } else {
              this.showErrorReq = true
              this.errorReqMsg = '请求节点表单字段权限失败'
            }
          }
        )
      })
    },
    //初始化
    initial() {
      //重置 表单权限配置
      this.formPermission = {}
      // 发起状态查询获取最新表单json，非发起状态获取发起时的历史表单json
      let requestFunc =
        this.$route.params.type === 'add'
          ? getCustomFormConfig({ formKey: this.formKey })
          : getHistoryCustomFormConfig({
              formKey: this.formKey,
              bizId: this.bizId
            })
      requestFunc.then(async (res) => {
        if (res.status && res.data) {
          //获取 表单基本属性、配置
          this.isFakeCustom = res.data.formType == 0 ? false : true
          eventBus.$emit('setIsFakeCustom', this.isFakeCustom)
          this.formName = res.data.formName
          //告知父组件表单名称
          this.$emit('setFormName', res.data.formName)
          this.modelKey = res.data.modelKey
          this.customFlowConfig.isCustom = res.data.formType == 0 ? true : false
          let formObj = JSON.parse(res.data.formDesign).fields
          //不在填写阶段不出现关联数据
          if (this.type !== 'add') {
            formObj = formObj.filter((field) => {
              return field.__config__.tagAttribute !== 'associate-data'
            })
          }
          if (this.type !== 'view') {
            formObj.forEach((item) => {
              if (
                item.__config__.tagAttribute == 'select' &&
                item.optionContentType == 'associate' &&
                Object.keys(this.linkageData).length > 0
              ) {
                let linkageObj = this.linkageData[item.__vModel__]
                let linkageArr = []
                linkageObj.fields.forEach((field) => {
                  let linkageTagAttribute = linkageObj.tagAttribute
                  let obj = {}
                  obj.label = transfer(
                    linkageTagAttribute[item.dataConfig.relateFormFields],
                    field[item.dataConfig.relateFormFields]
                  )
                  obj.value = obj.label
                  linkageArr.push(obj)
                })
                // 需要去重
                item.__slot__.options = unique(linkageArr)
              }
            })
          }

          this.$refs.parser.dealResponseFormObj(formObj)
          let formAttr = isJSON(res.data.formAttr)
            ? JSON.parse(res.data.formAttr)
            : []
          //调整formAttr的格式方便parser组件解析
          formAttr.forEach((item) => {
            item.rules = []
            item.ruleGroup.forEach((ruleGroupItem) => {
              ruleGroupItem.rules.forEach((ruleItem, index) => {
                if (index === 0) {
                  ruleItem.spliceType = '||'
                  item.rules.push(ruleItem)
                } else {
                  ruleItem.spliceType = '&&'
                  item.rules.push(ruleItem)
                }
              })
            })
            delete item.ruleGroup
          })
          this.formConf = {
            formAttr: formAttr,
            fields: formObj,
            ...JSON.parse(res.data.formDesign).formConf
          }
          formObj.forEach((item) => {
            this.formPermission[item.__vModel__] = 'modify'
          })
          //除了新增表单 其他类型时 还需要获取对应数据
          // if (this.type === 'execute' || this.type === 'add') {
          //根据当前taskKey和modelKey 查询当前节点表单字段权限信息
          if (!this.isFakeCustom) {
            let {
              formPermission,
              detailPermission
            } = await this.getNodePermission()
            if (typeof formPermission === 'string') {
              formPermission = JSON.parse(formPermission)
            }
            if (typeof detailPermission === 'string') {
              detailPermission = JSON.parse(detailPermission)
            }
            this.detailPermission = detailPermission
            if (this.type !== 'add') {
              formObj.forEach((item) => {
                this.formPermission[item.__vModel__] = 'readonly'
              })
            }
            this.formPermission = Object.assign(
              this.formPermission,
              formPermission
            )
          }
          if (this.taskId && this.type === 'execute') {
            // 若有taskId则获取当前任务节点名称
            getUserTaskDetail(this.taskId).then((res) => {
              if (res.status && res.data.taskName) {
                this.taskNodeName = res.data.taskName
                //告知父组件taskNodeName
                this.$emit('setTaskNodeName', res.data.taskName)
              }
            })
          }
          if (this.type !== 'add') {
            let data = await this.initialForm()
            this.$refs.parser.fillFormData(this.formConf, data) //数据回填
          }
          // }
          this.loading = false
          this.key = +new Date() //通过Key刷新
        } else {
          this.showErrorReq = true
          this.errorReqMsg = '请求表单数据失败'
          this.$message({
            type: 'error',
            message: this.LANG.NO_DATA,
            showClose: true
          })
        }

        //获取流程comments
        if (this.type !== 'add' && !this.isFakeCustom) {
          this.loading = true
          let data = this.processInstanceId
            ? { processInstanceId: this.processInstanceId }
            : { taskId: this.taskId, bizId: this.bizId }
          getProcessHistory(data).then((res) => {
            if (res.status && res.data) {
              this.processInstanceId = res.data[0].id
              this.comments = res.data.map((item) => {
                switch (item.approveState) {
                  case 'commit':
                    item.approveStateName = this.LANG.COMMIT
                    break
                  case 'todo':
                    item.approveStateName = this.LANG.TODO
                    break
                  case 'agree':
                    item.approveStateName = this.LANG.AGREE //同意
                    break
                  case 'skip':
                    item.approveStateName = this.LANG.SKIP //自动跳过
                    break
                  case 'reject':
                    item.approveStateName = this.LANG.REJECT //退回
                    break
                  default:
                    item.approveStateName
                }
                return item
              })
            } else {
              this.showErrorReq = true
              this.errorReqMsg = '请求流程审批节点信息失败'
              this.comments = []
            }
          })
          getHistoryNodes({ taskId: this.taskId, bizId: this.bizId }).then(
            (res) => {
              this.flowInfo = Object.assign(this.flowInfo, res.data)
            }
          )
          this.loading = false
        }
      })
    },
    //预览初始化
    previewInitial() {
      //重置 表单权限配置
      this.formPermission = {}
      let designInfo = this.formDesign
      // 发起状态查询获取最新表单json，非发起状态获取发起时的历史表单json

      //获取 表单基本属性、配置
      this.isFakeCustom = designInfo.formType == 0 ? false : true
      eventBus.$emit('setIsFakeCustom', this.isFakeCustom)
      this.formName = designInfo.formName
      //告知父组件表单名称
      this.$emit('setFormName', designInfo.formName)
      this.modelKey = designInfo.modelKey
      this.customFlowConfig.isCustom = designInfo.formType == 0 ? true : false
      let formObj = JSON.parse(designInfo.formDesign).fields

      if (this.type !== 'view') {
        formObj.forEach((item) => {
          if (
            item.__config__.tagAttribute == 'select' &&
            item.optionContentType == 'associate' &&
            Object.keys(this.linkageData).length > 0
          ) {
            let linkageObj = this.linkageData[item.__vModel__]
            let linkageArr = []
            linkageObj.fields.forEach((field) => {
              let linkageTagAttribute = linkageObj.tagAttribute
              let obj = {}
              obj.label = transfer(
                linkageTagAttribute[item.dataConfig.relateFormFields],
                field[item.dataConfig.relateFormFields]
              )
              obj.value = obj.label
              linkageArr.push(obj)
            })
            // 需要去重
            item.__slot__.options = unique(linkageArr)
          }
        })
      }

      this.$refs.parser.dealResponseFormObj(formObj)
      let formAttr = isJSON(designInfo.formAttr)
        ? JSON.parse(designInfo.formAttr)
        : []
      //调整formAttr的格式方便parser组件解析
      formAttr.forEach((item) => {
        item.rules = []
        item.ruleGroup.forEach((ruleGroupItem) => {
          ruleGroupItem.rules.forEach((ruleItem, index) => {
            if (index === 0) {
              ruleItem.spliceType = '||'
              item.rules.push(ruleItem)
            } else {
              ruleItem.spliceType = '&&'
              item.rules.push(ruleItem)
            }
          })
        })
        delete item.ruleGroup
      })
      this.formConf = {
        formAttr: formAttr,
        fields: formObj,
        ...JSON.parse(designInfo.formDesign).formConf
      }
      formObj.forEach((item) => {
        this.formPermission[item.__vModel__] = 'modify'
      })
      //除了新增表单 其他类型时 还需要获取对应数据
      // if (this.type === 'execute' || this.type === 'add') {
      //根据当前taskKey和modelKey 查询当前节点表单字段权限信息
      if (!this.isFakeCustom) {
        let { formPermission, detailPermission } = this.getNodePermission() //表单字段权限
        if (typeof formPermission === 'string') {
          formPermission = JSON.parse(formPermission)
        }
        if (typeof detailPermission === 'string') {
          detailPermission = JSON.parse(detailPermission)
        }
        this.detailPermission = detailPermission

        this.formPermission = Object.assign(this.formPermission, formPermission)
      }

      // }
      this.loading = false
      this.key = +new Date() //通过Key刷新
    },
    initialForm() {
      return new Promise((resolve, reject) => {
        let data = {
          formKey: this.formKey,
          id: this.bizId
        }
        initialCustomForm(data).then((res) => {
          if (res.status) {
            let returnData = {}
            returnData = JSON.parse(JSON.stringify(res.data))
            this.bizId = res.data.id
            //删除基本字段
            const deleteArray = [
              'create_by',
              'create_date',
              'delete_flag',
              // 'id',
              'update_by',
              'update_date'
            ]
            deleteArray.forEach((item) => {
              this.$delete(returnData, item)
            })
            //拿到所有数据字段后，如果字段权限没有 Hide 也没有 modify  则默认readonly
            if (this.type !== 'edit' && this.type !== 'view') {
              Object.keys(returnData).forEach((key) => {
                if (!Object.keys(this.formPermission).includes(key)) {
                  // 普通流程自定义表单暂存后进入任务待办不请求permission接口但需要给modify权限
                  let permission =
                    this.$route.params.taskKey == 'FAWKES_START_EVENT'
                      ? 'modify'
                      : 'readonly'
                  this.$set(this.formPermission, key, permission)
                }
              })
            } else if (this.type === 'view') {
              this.formConf.fields.forEach((item) => {
                let vModel = item.__vModel__
                this.$set(this.formPermission, vModel, 'readonly')
              })
            }
            resolve(returnData)
          } else {
            this.showErrorReq = true
            this.errorReqMsg = '请求表单字段值失败'
            this.loading = false
          }
        })
      })
    },
    openAssociateDialog(vModel) {
      this.associateDataVisible = true
      this.clickModel = vModel
    },
    mapFormData(data) {
      // 选中数据后根据当前选中的关联数据组件的规则去映射数据到当前表单，修改formConf和formData
      this.formConf.fields.forEach((item) => {
        if (item.__vModel__ == this.clickModel) {
          this.mapRules = item.dataConfig.matchingParams
        }
      })
      this.mapRules.forEach((rule) => {
        this.assignValue(
          rule.targetField,
          rule.sourceField,
          data[rule.sourceField]
        )
      })
      this.$refs.parser.fillFormData(this.formConf, this.formData)
      this.$refs.parser.resetForm()
    },
    // 关联数据规则确定后的映射赋值操作
    assignValue(targetField, sourceField, sourceFieldVal) {
      this.formConf.fields.forEach((item) => {
        if (item.__vModel__ == targetField && sourceFieldVal && targetField) {
          item.__config__.defaultValue = sourceFieldVal
          this.formData[targetField] = sourceFieldVal
        }
      })
    }
  },
  created() {
    //eventBus必须在beforeDesdroy中取消订阅
    eventBus.$on('setFlowCanvasVisible', (val) => {
      this.flowCanvasVisible = val
    })
    eventBus.$on('submit', this.submit)
    eventBus.$on('saveDraft', this.saveDraft)
    eventBus.$on('success', (type) => {
      this.onSuccess(type)
    })
  },
  mounted() {
    //监听form-upload的上传事件
    this.$on('uploading', (fileId) => {
      //上传文件时，将文件id加入到uploadingList中
      this.uploadingList.push(fileId)
    })
    this.$on('uploaded', (fileId) => {
      //上传成功后,将文件id从uploadingList中移除
      const index = this.uploadingList.indexOf(fileId)
      if (index > -1) {
        this.uploadingList.splice(index, 1)
      }
    })
    if (!this.isPreview) {
      getAssociateData({ formKey: this.formKey }).then((res) => {
        if (res.status) {
          this.linkageData = res.data
        }
        //初始化
        this.initial()
      })
    } else {
      this.type = 'add'
      this.previewInitial()
    }
  },
  beforeDestroy() {
    eventBus.$off('submit')
    eventBus.$off('setFlowCanvasVisible')
    eventBus.$off('saveDraft')
    eventBus.$off('success')
  }
}
</script>
<style lang="scss" scoped>
::v-deep .no-flow-chart {
  *[aria-controls*='pane-flow'] {
    display: none;
  }
}
.fawkes-custom-diagram-button {
  text-align: center;
}
</style>
